package com.cimctech.socketdemo;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Timer;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.cimctech.socketdemo.schedule.HeartbeatSchedule;
import com.cimctech.socketdemo.schedule.PositionSchedule;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity----";
    private TextView tv1 = null;
    Handler mhandler;
    Handler mhandlerSend;
    boolean isRun = true;
    EditText edtsendms;
    Button btnsend;
    private String sendstr = "";
    SharedPreferences sp;
    Button btnSetting;
    private Context ctx;
    Socket socket;
    PrintWriter out;
    BufferedReader in;
    SocketThread socketThread;

    private Button btnStopSend;
    private Timer heatbeatTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1 = findViewById(R.id.tv1);
        btnsend = findViewById(R.id.button1);
        ctx = MainActivity.this;
        edtsendms = findViewById(R.id.editText1);
        btnSetting = findViewById(R.id.button2);
        btnStopSend = findViewById(R.id.btn_stop_send);



        mhandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                try {
                    Log.e(TAG, "mhandler接收到msg=" + msg.what);
                    if (msg.obj != null) {
                        String s = msg.obj.toString();
                        if (s.trim().length() > 0) {
                            Log.e(TAG, "mhandler接收到obj=" + s);
                            Log.e(TAG, "开始更新UI");
                            tv1.append("Server:" + s);
                            Log.e(TAG, "更新UI完毕");
                        } else {
                            Log.i(TAG, "没有数据返回不更新");
                        }
                    }
                } catch (Exception ee) {
                    Log.e(TAG, "加载过程出现异常");
                    ee.printStackTrace();
                }
            }
        };
        mhandlerSend = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                try {
                    Log.e(TAG, "mhandlerSend接收到msg.what=" + msg.what);
                    String s = msg.obj.toString();
                    if (msg.what == 1) {
                        tv1.append("\n ME: " + s + "      发送成功");
                    } else {
                        tv1.append("\n ME: " + s + "     发送失败");
                    }
                } catch (Exception ee) {
                    Log.e(TAG, "加载过程出现异常");
                    ee.printStackTrace();
                }
            }
        };
        startSocket();

        startSendHeartbeat();
        btnsend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 发送数据
                Log.e(TAG, "准备发送数据");
//                sendstr = edtsendms.getText().toString().trim();
//                socketThread.Send(sendstr);
                startTimerTask();

            }
        });
        btnSetting.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 跳转到设置界面
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, SettingActivity.class);
                Log.e(TAG, "跳转至设置界面");
                ctx.startActivity(intent);// 打开新界面

            }
        });

        btnStopSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                stopTimerTask();
            }
        });

    }

    Timer timer;

    private void startTimerTask() {
        if (timer == null) {
            timer = new Timer();

            timer.schedule(new PositionSchedule(socketThread), 0, 30000);
        }


    }

    private void stopTimerTask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void startSocket() {
        socketThread = new SocketThread(mhandler, mhandlerSend, ctx);
        socketThread.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.client, menu);
        return true;
    }

    private void stopSocket() {
        socketThread.isRun = false;
        socketThread.close();
        socketThread = null;
        Log.e(TAG, "Socket已终止");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e(TAG, "start onStart~~~");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e(TAG, "start onRestart~~~");
        startSocket();
        startSendHeartbeat();

    }


    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "start onStop~~~");
        stopSendHeartbeat();
        stopSocket();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopSendHeartbeat();
        stopSocket();
        Log.e(TAG, "start onDestroy~~~");

    }


    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x01:

                    break;

                default:
                    break;
            }
        }
    };


    /**
     * 开始发送心跳包
     */
    private void startSendHeartbeat() {
        if (heatbeatTimer == null) {
            heatbeatTimer = new Timer();
            heatbeatTimer.schedule(new HeartbeatSchedule(socketThread), 3000, 30000);
        }
    }

    private void stopSendHeartbeat() {
        if (heatbeatTimer != null) {
            heatbeatTimer.cancel();
            heatbeatTimer = null;
        }

    }


}
